package com.company.nuwa.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;

/**
 * <p>crc32</p>
 *
 * @author Lionel Lee
 * @version 1.0: Crc32Utils.java
 * @date 2021/5/16  10:11
 */
@Slf4j
public class Crc32Utils {

    public static String getCRC32(InputStream in) {
        CRC32 crc32 = new CRC32();
        CheckedInputStream checkedinputstream = null;
        String crc = null;
        try {
            checkedinputstream = new CheckedInputStream(in, crc32);
            while (checkedinputstream.read() != -1) {
            }
            crc = Long.toHexString(crc32.getValue()).toUpperCase();
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            if (checkedinputstream != null) {
                try {
                    checkedinputstream.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }
        return crc;
    }

    public static String getCRC32(String fileUri) {
        CRC32 crc32 = new CRC32();
        FileInputStream fileinputstream = null;
        CheckedInputStream checkedinputstream = null;
        String crc = null;
        try {
            fileinputstream = new FileInputStream(new File(fileUri));
            checkedinputstream = new CheckedInputStream(fileinputstream, crc32);
            while (checkedinputstream.read() != -1) {
            }
            crc = Long.toHexString(crc32.getValue()).toUpperCase();
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            if (fileinputstream != null) {
                try {
                    fileinputstream.close();
                } catch (IOException e2) {
                    log.error(e2.getMessage());
                }
            }
            if (checkedinputstream != null) {
                try {
                    checkedinputstream.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }
        return crc;
    }
}
